﻿@{
    // Cache the image for a minute
    Response.OutputCache(60);

    var tagName = UrlData[0];

    var db = Database.Open("PhotoGallery");
    var tag = db.Query("SELECT TagName FROM Tags WHERE TagName = @0", tagName);
    var photoList = db.Query(@"SELECT TOP(3) Photos.FileContents 
                               FROM Photos, Photos_Tags 
                               WHERE Photos.Id = Photos_Tags.Photos_Id AND Photos_Tags.Tags_TagName = @0", tagName).Shuffle().ToList();

    if (tag != null && photoList.Count > 0) {
        using (MultiThumbnailGenerator generator = new MultiThumbnailGenerator()) {
            foreach (var photo in photoList) {
				using (var imageStream = new System.IO.MemoryStream(photo.FileContents)) {
                    using (var image = System.Drawing.Image.FromStream(imageStream)) {
                        generator.AddImage(image);
                    }
                }
            }

            using (var outStream = new System.IO.MemoryStream()) {
                generator.WritePngToStream(outStream);
                var image = new WebImage(outStream);
                image.Write();
            }
        }
    } else {
        // no photos - hopefully user will never see this
        Response.Redirect("~/Shared/gallery-empty.png");
    }
}